package main

import (
	"bufio"
	"encoding/json"
	"fmt"
	"io"
	"io/ioutil"
	"os"
	"os/exec"
	"path"
	"strconv"
	"strings"
)

var mp3path string
var flvpath string
var time string

func main() {

	conv()
}

func conv() {

	//获取时长
	// ffprobe -v quiet -print_format json -show_format -show_streams input.mp4

	//转化 1
	// .\ffmpeg.exe -loop 1 -r 1 -t 220 -f image2 -i Picture.jpg -c:v libx264 -crf 24 -y SinglePictureVideo.mp4
	// .\ffmpeg.exe -i ttf.mp4 -i 2.mp3 -c:v copy -c:a copy -y 2_SP.flv

	//转化2
	// shell := `ffmpeg -i 2.mp3 -loop 1 -r 1 -f image2 -i 2.jpg -acodec aac -strict -2 -vcodec libx264 -ar 22050 -ab 128k -ac 2 -pix_fmt yuvj420p -crf 24 -y out.flv`

	//水印
	// .\ffmpeg -y -i SinglePictureVideo.mp4 -vf "drawtext=text='hello':fontfile=msyh.ttc:fontsize=60:fontcolor=yellow@0.8:x=w-tw-16:y=h-th-16" -b:v 1024k ttf.mp4

	//直播
	//ffmpeg -re -i 2_SP.flv -vcodec copy -acodec aac -b:a 192k -f flv "rtmp://......"
	dirList, err := ioutil.ReadDir("./mp3")
	if err != nil {
		fmt.Println(err)
	}
	for i, v := range dirList {
		fn := getfilename(v.Name())
		fmt.Println(fn)
		mp3path = `mp3/` + v.Name()
		flvpath = `flv/` + strconv.Itoa(i) + `.flv`

		execffprobeCommand("ffprobe", "-v", "quiet", "-print_format", "json", "-show_format", "-show_streams", mp3path)
		fmt.Println(time)

		execffmpegCommand("ffmpeg", "-loop", "1", "-r", "5", "-t", time, "-f", "image2", "-i", "Picture.jpg", "-c:v", "libx264", "-crf", "24", "-y", "tmp/s1.mp4")
		execffmpegCommand("ffmpeg", "-y", "-i", "tmp/s1.mp4", "-vf", "drawtext=text=`"+fn+"`:fontfile=msyh.ttc:fontsize=60:fontcolor=yellow@0.8:x=w-tw-16:y=h-th-16", "-b:v", "1024k", "tmp/s2.mp4")
		removetmp(`tmp/s1.mp4`)
		execffmpegCommand("ffmpeg", "-i", "tmp/s2.mp4", "-i", mp3path, "-c:v", "copy", "-c:a", "copy", "-y", flvpath)
		removetmp(`tmp/s2.mp4`)
	}
}
func getfilename(name string) string {
	fnbase := path.Base(name)
	fnext := path.Ext(name)
	return strings.TrimSuffix(fnbase, fnext)
}

func removetmp(file string) {
	err := os.Remove(file) //删除文件test.txt
	if err != nil {
		//如果删除失败则输出 file remove Error!
		fmt.Println("file remove Error!")
		//输出错误详细信息
		fmt.Printf("%s", err)
	} else {
		//如果删除成功则输出 file remove OK!
		fmt.Println("file remove OK!")
	}
}
func execffmpegCommand(c string, commandName ...string) bool {
	// cmd := exec.Command("ffmpeg", commandName...)
	cmd := exec.Command(c, commandName...)
	//显示运行的命令
	fmt.Println(cmd.Args)
	cmd.Start()
	cmd.Wait()
	return true
}

func execffprobeCommand(c string, commandName ...string) bool {
	// cmd := exec.Command("ffmpeg", commandName...)
	cmd := exec.Command(c, commandName...)
	//显示运行的命令
	fmt.Println(cmd.Args)
	stdout, err := cmd.StdoutPipe()
	if err != nil {
		fmt.Println(err)
		return false
	}
	cmd.Start()
	reader := bufio.NewReader(stdout)
	//实时循环读取输出流中的一行内容
	var str string
	for {
		line, err2 := reader.ReadString('\n')
		if err2 != nil || io.EOF == err2 {
			break
		}
		// fmt.Print(line)
		str = str + line
	}
	var dat AutoGenerated
	if err := json.Unmarshal([]byte(str), &dat); err == nil {
		time = dat.Streams[0].Duration
	} else {
		fmt.Println(err)
	}
	cmd.Wait()
	return true
}

type AutoGenerated struct {
	Streams []struct {
		Index          int    `json:"index"`
		CodecName      string `json:"codec_name"`
		CodecLongName  string `json:"codec_long_name"`
		CodecType      string `json:"codec_type"`
		CodecTimeBase  string `json:"codec_time_base"`
		CodecTagString string `json:"codec_tag_string"`
		CodecTag       string `json:"codec_tag"`
		SampleFmt      string `json:"sample_fmt,omitempty"`
		SampleRate     string `json:"sample_rate,omitempty"`
		Channels       int    `json:"channels,omitempty"`
		ChannelLayout  string `json:"channel_layout,omitempty"`
		BitsPerSample  int    `json:"bits_per_sample,omitempty"`
		RFrameRate     string `json:"r_frame_rate"`
		AvgFrameRate   string `json:"avg_frame_rate"`
		TimeBase       string `json:"time_base"`
		StartPts       int    `json:"start_pts"`
		StartTime      string `json:"start_time"`
		DurationTs     int64  `json:"duration_ts"`
		Duration       string `json:"duration"`
		BitRate        string `json:"bit_rate,omitempty"`
		Disposition    struct {
			Default         int `json:"default"`
			Dub             int `json:"dub"`
			Original        int `json:"original"`
			Comment         int `json:"comment"`
			Lyrics          int `json:"lyrics"`
			Karaoke         int `json:"karaoke"`
			Forced          int `json:"forced"`
			HearingImpaired int `json:"hearing_impaired"`
			VisualImpaired  int `json:"visual_impaired"`
			CleanEffects    int `json:"clean_effects"`
			AttachedPic     int `json:"attached_pic"`
			TimedThumbnails int `json:"timed_thumbnails"`
		} `json:"disposition"`
		Width              int    `json:"width,omitempty"`
		Height             int    `json:"height,omitempty"`
		CodedWidth         int    `json:"coded_width,omitempty"`
		CodedHeight        int    `json:"coded_height,omitempty"`
		HasBFrames         int    `json:"has_b_frames,omitempty"`
		SampleAspectRatio  string `json:"sample_aspect_ratio,omitempty"`
		DisplayAspectRatio string `json:"display_aspect_ratio,omitempty"`
		PixFmt             string `json:"pix_fmt,omitempty"`
		Level              int    `json:"level,omitempty"`
		ColorRange         string `json:"color_range,omitempty"`
		Refs               int    `json:"refs,omitempty"`
		Tags               struct {
			Comment string `json:"comment"`
		} `json:"tags,omitempty"`
	} `json:"streams"`
	Format struct {
		Filename       string `json:"filename"`
		NbStreams      int    `json:"nb_streams"`
		NbPrograms     int    `json:"nb_programs"`
		FormatName     string `json:"format_name"`
		FormatLongName string `json:"format_long_name"`
		StartTime      string `json:"start_time"`
		Duration       string `json:"duration"`
		Size           string `json:"size"`
		BitRate        string `json:"bit_rate"`
		ProbeScore     int    `json:"probe_score"`
		Tags           struct {
			Language    string `json:"language"`
			Encoder     string `json:"encoder"`
			Comment     string `json:"comment"`
			Album       string `json:"album"`
			Title       string `json:"title"`
			Artist      string `json:"artist"`
			AlbumArtist string `json:"album_artist"`
			Track       string `json:"track"`
		} `json:"tags"`
	} `json:"format"`
}
